package backend_0011_2;

public class Attack {

    public static void main(String[] args) {
        Player Ava=new Player(100,"Ava");
        Invader1 invader1=new Invader1(Ava);
        Invader2 invader2=new Invader2(Ava);
        new Thread(invader2,"Creep-A").start();
        new Thread(invader1,"Creep-B").start();

    }
}

//攻击者1
class Invader1 implements Runnable{
    Player player;
    public Invader1(Player player){
        this.player=player;
    }

    @Override
    public void run() {
        //同步块
        synchronized (player){
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName()+":attack "+player.name);
                player.hp-=20;
                System.out.println(Thread.currentThread().getName()+":当前player的hp值="+player.hp);
                if(player.hp==0){
                    System.out.println(Thread.currentThread().getName()+":player is dead.");
                    System.out.println(Thread.currentThread().getName()+":end.");
                    break;
                }
            }
        }
    }
}
//攻击者2
class Invader2 implements Runnable{
    Player player;
    public Invader2(Player player){
        this.player=player;
    }

    @Override
    public synchronized void run() {
        player.at(player);
    }
}
//玩家
class Player{
    String name;
    int hp;
    public Player(int hp,String name){
        this.hp=hp;
        this.name=name;
    }
    //同步方法
    public synchronized void at(Player player){
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName()+":attack "+player.name);
            player.hp-=20;
            System.out.println(Thread.currentThread().getName()+":当前player的hp值="+player.hp);
            if(player.hp==0){
                System.out.println(Thread.currentThread().getName()+":player is dead.");
                System.out.println(Thread.currentThread().getName()+":end.");
                break;
            }
        }

    }
}
